#!/bin/bash
###########################################################################
# Copyright 2019 Broadcom. The term "Broadcom" refers to Broadcom Inc.    #
# and/or its subsidiaries.                                                #
#                                                                         #
# Licensed under the Apache License, Version 2.0 (the "License");         #
# you may not use this file except in compliance with the License.        #
# You may obtain a copy of the License at                                 #
#                                                                         #
#   http://www.apache.org/licenses/LICENSE-2.0                            #
#                                                                         #
# Unless required by applicable law or agreed to in writing, software     #
# distributed under the License is distributed on an "AS IS" BASIS,       #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.#
# See the License for the specific language governing permissions and     #
# limitations under the License.                                          #
###########################################################################
ZTP_ENGINE=/usr/lib/ztp/ztp-engine.py
ztp_engine_pid=""

sighandle()
{
    if [ "$ztp_engine_pid" != "" ]; then
        wait $ztp_engine_pid
    fi
    exit 0
}

start()
{
    # Enable debug level logging
    [ "${DEBUG}" = "yes" ] && DEBUG_ARGS="-d"

    # Start ZTP service in restricted unit test mode
    [ "${TEST_MODE}" = "yes" ] && TEST_ARGS="-t"

    # Custom ztp_cfg.json file
    [ "${CONFIG_JSON}" != "" ] && CONFIG_JSON_ARGS="-C ${CONFIG_JSON}"

    if [ "${COVERAGE}" = "yes" ]; then
        if which python3-coverage > /dev/null; then
            [ "${COVERAGE_CMD}" = "" ] && COVERAGE_EXP="python3-coverage run --append"
            [ "${COVERAGE_CMD}" != "" ] && COVERAGE_EXP=${COVERAGE_CMD}
            echo "Starting ZTP service with code coverage measurement tool"
        else
            echo "Use 'apt-get install python3-coverage' to start ZTP service with code coverage measurement tools"
            echo "Starting ZTP service without code coverage measurement tool "
        fi
    fi

    # Kickstart ZTP service daemon
    ${COVERAGE_EXP} ${ZTP_ENGINE} ${DEBUG_ARGS} ${TEST_ARGS} ${CONFIG_JSON_ARGS} &

    ztp_engine_pid=$!
    wait "$ztp_engine_pid"
}

trap 'sighandle'  TERM INT

start

exit 0
